package com.example.usermanagement.util;

import java.io.Serializable;
import java.util.Objects;

public final class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private static final String successMsg = "操作成功";
    private static final int successCode = 0;
    private static final int errorCode = 1;

    private Integer code;   // 业务状态码 0-成功 1-失败
    private String message; // 提示信息
    private T data; // 响应数据

    public Result(Integer code, String message, T data) {
        if (code == null || message == null) {
            throw new IllegalArgumentException("Code and message cannot be null");
        }
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public Result() {}

    // 快速返回操作成功响应结果（带响应数据）
    public static <T> Result<T> success(T data) {
        return new Result<>(successCode, successMsg, data);
    }

    // 快速返回操作成功响应结果
    public static Result<Void> success() {
        return new Result<>(successCode, successMsg, null);
    }

    // 快速返回操作失败响应结果（带提示信息）
    public static Result<Void> error(String message) {
        if (message == null || message.isEmpty()) {
            throw new IllegalArgumentException("Message cannot be null or empty");
        }
        return new Result<>(errorCode, message, null);
    }

    // 快速返回操作失败响应结果
    public static <T> Result<T> ofError(String message) {
        return new Result<>(errorCode, message, null);
    }

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Result<?> result = (Result<?>) o;
        return Objects.equals(code, result.code) &&
                Objects.equals(message, result.message) &&
                Objects.equals(data, result.data);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code, message, data);
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
